//
//  LoginViewController.m
//  MyPizzaMobile
//
//  Created by Stanislav on 2/15/13.
//  Copyright (c) 2013 Stanislav. All rights reserved.
//

#import "LoginViewController.h"

@interface LoginViewController ()
@property (readwrite) RequestManager* requestManager;
@end

@implementation LoginViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.requestManager = [RequestManager requestManagerInstance];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setUsernameTextField:nil];
    [self setPasswordTextField:nil];
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    self.usernameTextField.text = [self.requestManager unescape:[defaults objectForKey:@"username"]];
    self.passwordTextField.text = [self.requestManager unescape:[defaults objectForKey:@"password"]];
}

- (IBAction)nextFieldPressed:(UITextField *)sender
{
    if(sender == self.usernameTextField)
    {
        [self.passwordTextField becomeFirstResponder];
    }
    else if(sender == self.passwordTextField)
    {
        [self.passwordTextField resignFirstResponder];
        [self sendLoginInfo];
    }
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch * touch = [touches anyObject];
    if(touch.phase == UITouchPhaseBegan) {
        [self.usernameTextField resignFirstResponder];
        [self.passwordTextField resignFirstResponder];
    }
}
- (void) sendLoginInfo
{
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
    [dict setObject:(self.usernameTextField.text?self.usernameTextField.text:@"") forKey:@"username"];
    [dict setObject:(self.passwordTextField.text?self.passwordTextField.text:@"") forKey:@"password"];
    if([self.requestManager sendLoginWithDict:[dict copy]])
    {
        [self performSegueWithIdentifier:@"login" sender:nil];
    }
}

- (IBAction)logButtonPressed:(UIButton *)sender {
    [self sendLoginInfo];
}

- (IBAction)dissmissKeyboard:(UITextField*)sender {
    [sender resignFirstResponder];
}
@end
